﻿using ImageManager.Common;
using ImageManager.DBAccess;
using ImageManager.Model;

namespace ImageManager.ImageService
{
    public class DownloadHistoryServiceProvider : BaseServiceProvider<DownloadHistoryModel>
    {
        public bool WasDownload(string imagePk)
        {
            var usr = ServiceLoader.GetService<OnlineUser>();
            var first = qryInstance.Where(CondCollection.True()
                .Eq(nameof(DownloadHistoryModel.Image), imagePk)
                .Eq(nameof(DownloadHistoryModel.Creator), usr.UserId)).First();
            return first != null;
        }
        public override void Save(DownloadHistoryModel data)
        {
            var usr = ServiceLoader.GetService<OnlineUser>();
            if (data.Creator == usr.UserId) return;
            if (WasDownload(data.Image)) return;
            base.Save(data);
            var imageService = ServiceLoader.GetService<ImageServiceProvider>();
            imageService.UpdateHeat(data.Image);
        }

        public Stream ToExcel(string period)
        {
            string sqlstr = "SELECT A.CREATEDATE 下载日期,B.USERNAME 下载人,C.SERIESNAME 系列名,C.PRICE 上传点数,A.PAY 下载点数,D.USERNAME 上传人,C.CREATEDATE 上传时间 " +
                " FROM T_DOWNLOADHISTORY A " +
                " LEFT JOIN T_USER B ON A.CREATOR = B.PK" +
                " LEFT JOIN T_IMAGE C ON A.IMAGE = C.PK " +
                " LEFT JOIN T_USER D ON C.CREATOR = D.PK" +
                " WHERE A.CREATEDATE LIKE @P";
            return Utils.ToExcelStream(qryInstance.ToTable(sqlstr, period + "%"));
        }
    }
}
